import React, { useCallback, useEffect, useState, useRef } from 'react'
import { sleep, amapReady } from '../utils'
import css from './runtime.less'

const previewData = [
  {
    id: 1,
    lnglat: [121.39471, 37.535519],
    title: '万达广场(烟台芝罘店)'
  },
  {
    id: 2,
    lnglat: [121.459188, 37.475508],
    title: '烟台大学'
  }
]

export default function ({ env, data, outputs, inputs }) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<any>(null)
  const markersRef = useRef<any>([])
  const markersRecord = useRef<any[] | null>([])
  const previewMarker = useRef<any>(null)
  const previewInfoWnd = useRef<any>(null)
  const infoWndContent = useRef<HTMLDivElement | null>(null)
  const getCenter = () => {
    const { lng, lat } = data
    if (lng && lat) {
      return [lng, lat]
    }
    return [121.39471, 37.535519]
  }

  const createInfoWnd = () => {
    const map = mapRef.current
    if (!map) return
    //信息窗体的内容
    var content = document.createElement('div')
    content.classList.add(css.infownd)
    content.innerText = 'xxxxxx信息科技有限公司'
    Object.assign(content.style, data.infoWndStyle)
    content.style.setProperty('--back-color', content.style.backgroundColor)
    infoWndContent.current = content
    //创建 infoWindow 实例
    var infoWindow = new AMap.InfoWindow({
      isCustom: true,
      content: content, //传入字符串拼接的 DOM 元素
      anchor: 'top-left',
      offset: env.edit ? new AMap.Pixel(-13, -30) : new AMap.Pixel(-23, -90) //以 icon 的 [center bottom] 为原点
    })
    previewInfoWnd.current = infoWindow

    if (env.edit) {
      const center = getCenter()
      //打开信息窗体
      infoWindow.open(map, center)
    }
  }

  const createPreviewMarker = () => {
    const map = mapRef.current
    if (!map || !env.edit) return
    const center = getCenter()
    const marker = new AMap.Marker({
      position: center,
      offset: new AMap.Pixel(-13, -30) //以 icon 的 [center bottom] 为原点
    })
    marker.setMap(map)
    previewMarker.current = marker
  }

  const showMarkers = () => {
    const markers = markersRef.current
    console.log(markers)
    const map = mapRef.current
    if (!map || !Array.isArray(markers)) return
    if (Array.isArray(markersRecord.current)) {
      markersRecord.current.forEach((item) => item?.setMap?.(null))
      markersRecord.current = null
    }
    markersRecord.current = markers.map((m) => {
      const marker = new AMap.Marker({
        map,
        position: m.lnglat,
        offset: new AMap.Pixel(-13, -30)
      })
      marker.on('mouseover', () => {
        infoWndContent.current!.innerText = m.title
        previewInfoWnd.current.open(map, m.lnglat)
      })
      marker.on('mouseout', () => {
        previewInfoWnd.current.close()
      })
      return marker
    })
  }

  useEffect(() => {
    if (infoWndContent.current) {
      Object.assign(infoWndContent.current.style, data.infoWndStyle)
      infoWndContent.current.style.setProperty('--back-color', infoWndContent.current.style.backgroundColor)
    }
  }, [data.infoWndStyle])

  useEffect(() => {
    const map = mapRef.current
    const marker = previewMarker.current
    const infoWnd = previewInfoWnd.current
    const center = getCenter()
    infoWnd?.setPosition?.(center)
    map?.setCenter?.(center)
    marker?.setPosition?.(center)
  }, [data.lng, data.lat])

  useEffect(() => {
    const container = containerRef.current
    if (!container) return
    let working = true
    let map: any = null
    amapReady().then(() => {
      if (!working) return
      const mapStyle = data.mapStyle || 'blue'
      map = new AMap.Map(container, {
        mapStyle: `amap://styles/${mapStyle}`,
        pitch: 0,
        features: ['bg', 'road'],
        zoom: 9,
        center: getCenter(),
        viewMode: '2D'
      })
      mapRef.current = map
      createInfoWnd()
      createPreviewMarker()
      showMarkers()
    })
    return () => {
      working = false
      map?.destroy?.()
      map = null
    }
  }, [])

  useEffect(() => {
    const map = mapRef.current
    const styleName = 'amap://styles/' + data.mapStyle || 'blue'
    map?.setMapStyle?.(styleName)
  }, [data.mapStyle])

  // 数据变化，数据格式 [{name:string,lnglat: [number,number]}]
  inputs['setMarkers']((val: any, outputRels: any) => {
    markersRef.current = val
    showMarkers()
    outputRels['onSetMarkersFinish'](val)
  })
  return (
    <div style={{width: '100%', height: '100%'}}>
      <div ref={containerRef} className={css.container}>
        loading...
      </div>
    </div>
  )
}
